'''
Usage:
    server.py
    server.py <port>

Options:
    -h --help show this

Example:
    server.py(defualt port is 10000)
    server.py <port>
'''

# !/usr/bin/env python3
# -*- coding: utf-8 -*-
# aim:    
# author: wangkaixuan
# email:  26554189525@qq.com 
# date:   2018/1/15

from socket import *
from time import ctime
from docopt import docopt
import os

port = 10000
PORT = 9898
BUFSIZE = 1024
ADDR = ('', PORT)

def use_Twisted():
    from twisted.internet import protocol,reactor
    class TSServProtocol(protocol.Protocol):
        def connectionMade(self): #当一个客户端连接上该服务器程序时执行
            clnt = self.clnt = self.transport.getPeer().host
            print('---connected from:',clnt)
        def dataReceived(self, data):#当服务器接收到客户端发送的数据时执行
            data = '[%s]%s' %(ctime(),data)
            print('recv data:',data)
            self.transport.write(data.encode())
    factory = protocol.Factory()#返回一个实例
    factory.protocol = TSServProtocol #新建的一个‘协议’
    print('waiting for connection---')
    reactor.listenTCP(port,factory)
    reactor.run()
def use_Twisted_ex2_4(port):
    from twisted.internet import protocol,reactor
    class TSServProtocol(protocol.Protocol):
        def connectionMade(self): #当一个客户端连接上该服务器程序时执行
            clnt = self.clnt = self.transport.getPeer().host
            print('---connected from:',clnt)
        def dataReceived(self, data):#当服务器接收到客户端发送的数据时执行
            data = '[%s]%s' %(ctime(),data)
            print('recv data:',data)
            self.transport.write(data.encode())
    factory = protocol.Factory()#返回一个实例
    factory.protocol = TSServProtocol #新建的一个‘协议’
    print('waiting for connection and listen port:',port)
    reactor.listenTCP(int(port),factory)
    reactor.run()
def use_Twisted_ex2_5(port):
    from twisted.internet import protocol,reactor
    class TSServProtocol(protocol.Protocol):
        def connectionMade(self): #当一个客户端连接上该服务器程序时执行
            clnt = self.clnt = self.transport.getPeer().host
            print('---connected from:',clnt)
        def dataReceived(self, data):#当服务器接收到客户端发送的数据时执行
            order = data.decode()
            if order == 'date':
                data = ctime()
                data = ('server\'s time now is ' + data).encode()
            if order == 'os':
                data = os.name
                data = ('server\'s is ' + data).encode()
            if order == 'ls':
                data = [x for x in os.listdir('.')]
                data = str(data)
                data = ('server\'s current dir:\n ' + data).encode()
            self.transport.write(data)
    factory = protocol.Factory()#返回一个实例
    factory.protocol = TSServProtocol #新建的一个‘协议’
    print('waiting for connection and listen port:',port)
    reactor.listenTCP(int(port),factory)
    reactor.run()

def use_Tcp():
    TcpSerSock = socket(AF_INET,SOCK_STREAM)
    TcpSerSock.bind(ADDR)
    TcpSerSock.listen(5)
    while(True):
        print('waiting for connection---')
        TcpCliSock,Addr = TcpSerSock.accept()
        print('connected from ',Addr)
        while(True):
            data = TcpCliSock.recv(BUFSIZE).decode()
            if not data:
                break
            tim = data + ' in ' +ctime()
            TcpCliSock.send(tim.encode())
        TcpCliSock.close()
    TcpSerSock.close()

def use_Udp():
    udpSerSock = socket(AF_INET, SOCK_DGRAM)
    udpSerSock.bind(ADDR)
    try:
        while (True):
            print('Waiting for message---')
            data, addr = udpSerSock.recvfrom(BUFSIZE)
            print('recv data=',data)
            print('recv addr=',addr)
            dat = data.decode() + ctime()
            udpSerSock.sendto(dat.encode(),addr)
        udpSerSock.close()
    except EOFError as f:
        print(f)

from socketserver import (TCPServer as TCP,StreamRequestHandler as SRH)
def use_SocketServer():
    class MyRequestHandler(SRH):
        def handle(self):
            print('connected from ',self.client_address)
            data = self.rfile.readline()
            print('data=',data)
            data = data.decode() + ctime()
            self.wfile.write(data.encode())
    TcpServ = TCP(ADDR,MyRequestHandler)
    print('waiting for connected---')
    TcpServ.serve_forever()

def ex2_4():
    argument = docopt(__doc__)
    port = argument.get('<port>')
    if not port:
        port = 10000
    print(port)
    use_Twisted_ex2_4(port)

def ex2_5():
    argument = docopt(__doc__)
    port = argument.get('<port>')
    if not port:
        port = 10000
    print(port)
    use_Twisted_ex2_5(port)

def ex2_6(): # 不能使用getservbyname函数
    argument = docopt(__doc__)
    port = argument.get('<port>')
    if not port:
        port = 10000
    udpSerSock = socket(AF_INET, SOCK_DGRAM)
    udpSerSock.bind(('',int(port)))
    try:
        while (True):
            print('Waiting for message---')
            data, addr = udpSerSock.recvfrom(BUFSIZE)
            print('recv data=',data)
            # print('from port:',socket.getservbyname('tcp'))

            dat = data.decode() + ctime()
            udpSerSock.sendto(dat.encode(),addr)
        udpSerSock.close()
    except EOFError as f:
        print(f)
# def ex2_7():
